/*****************************************************************************
 * file  : systask.c
 * creat : apleilx
 * note :
 * data  : 2019/07/02
 *******************************************************************************/

#include "ff.h"
#include "fat_file_opt.h"

/*****************************************************************************
 * @brief   const
 *****************************************************************************/
#define fil ((FIL *)obj)

/*****************************************************************************
 * @brief   fat_fil_open
 * @param   none
 * @return  non
 *****************************************************************************/
uint8_t fat_fil_open(void *obj, char *path, uint32_t mode)
{
	uint8_t st;

	st = FIL_OPT_ERR;

	switch (mode)
	{
	case FIL_OPEN_R:
		if (f_open(fil, path, FA_READ) == FR_OK)
			st = FIL_OPT_OK;
		break;
	case FIL_OPEN_W:
		if (f_open(fil, path, FA_WRITE | FA_OPEN_ALWAYS) == FR_OK)
			st = FIL_OPT_OK;
		break;
	case FIL_OPEN_WA:
		if (f_open(fil, path, FA_WRITE | FA_CREATE_ALWAYS) == FR_OK)
			st = FIL_OPT_OK;
		break;
	default:
		st = FIL_OPT_ERR;
		break;
	}

	return st;
}

/*****************************************************************************
 * @brief   fat_fil_close
 * @param   none
 * @return  non
 *****************************************************************************/
uint8_t fat_fil_close(void *obj)
{
	if (f_close(fil) == FR_OK)
	{
		return FIL_OPT_OK;
	}

	return FIL_OPT_ERR;
}

/*****************************************************************************
 * @brief   simp_fat_ext_file_size
 * @param   none
 * @return  non
 *****************************************************************************/
uint32_t fat_fil_size(void *obj)
{
	return fil->obj.objsize;
}

/*****************************************************************************
 * @brief   fat_fil_read
 * @param   none
 * @return  non
 *****************************************************************************/
uint8_t fat_fil_read(void *obj, void *buff, uint32_t len, uint32_t *len_back)
{
	if (f_read(fil, buff, len, len_back) == FR_OK)
	{
		return FIL_OPT_OK;
	}

	return FIL_OPT_ERR;
}

/*****************************************************************************
 * @brief   fat_fil_seek
 * @param   none
 * @return  non
 *****************************************************************************/
uint8_t fat_fil_seek(void *obj, uint32_t site)
{
	if (f_lseek(fil, site) == FR_OK)
	{
		return FIL_OPT_OK;
	}

	return FIL_OPT_ERR;
}

/*****************************************************************************
 * @brief   fat_fil_write
 * @param   none
 * @return  non
 *****************************************************************************/
uint8_t fat_fil_write(void *obj, void *buff, uint32_t len, uint32_t *len_back)
{
	if (f_write(fil, buff, len, len_back) == FR_OK)
	{
		return FIL_OPT_OK;
	}

	return FIL_OPT_ERR;
}
